package com.atguigu.springcloud.service.impl;

import com.atguigu.springcloud.dao.EmployeeRepository;
import com.atguigu.springcloud.entities.Employee;
import com.atguigu.springcloud.page.PageRequestConverter;
import com.atguigu.springcloud.page.SimplePage;
import com.atguigu.springcloud.page.SpringDataPageConverter;
import com.atguigu.springcloud.request.EmployeePageRequest;
import com.atguigu.springcloud.request.SaveEmployeeRequest;
import com.atguigu.springcloud.service.EmployeeService;
import com.atguigu.springcloud.utils.ModelMapperUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import java.util.List;

/**
 * Created by luojie on 2018/9/7.
 */
@Service
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeRepository employeeRepository;

    @Autowired
    private EntityManager entityManager;

    @Override
    public Employee save(SaveEmployeeRequest saveEmployeeRequest) {
        Employee employee =  ModelMapperUtil.getStrictModelMapper().map(saveEmployeeRequest, Employee.class);
        employee = employeeRepository.save(employee);
        return employee;
    }

    @Override
    public SimplePage<Employee> appPage(EmployeePageRequest pageRequest) {
        Pageable pageable = PageRequestConverter.convertToSpringDataPageable(pageRequest);
        Employee employee = ModelMapperUtil.get().map(pageRequest, Employee.class);

        Page<Employee> page = employeeRepository.findAll(Example.of(employee), pageable);

        return new SpringDataPageConverter<Employee>().convertToSimplePage(page);

    }

    @Override
    public Employee findById(String id) {
        String hql = "from Employee d where d.id='" + id + "'";
        Query query = entityManager.createQuery(hql);
        List<Employee> list = query.getResultList();
        if(list == null || list.size() == 0){
            return null;
        }
        return list.get(0);
    }

    @Override
    @Transactional
    public Employee save(Employee employee) {
        return employeeRepository.save(employee);
    }
}
